<script setup>

import {onMounted, reactive} from "vue";
import {entities_store, transactions_store} from '@/global_store';
import de from '@/assets/de.aac';
import tuf from '@/assets/tuf.aac';
import {play_audio} from "@/utils/audio";
import {ElTree} from "element-plus";
import 'element-plus/dist/index.css'

function pdf_filepath_to_file(pdf_filepath) {
    let result = {
        filepath: pdf_filepath,
    };
    let _match_result = pdf_filepath.match(/作业\/(.+?-.+?)\/(.+?)\/(.+?)\.pdf/);
    if (_match_result) {
        return {...result,
            is_standard: true,
            filedir: _match_result[1],
            filetype: _match_result[2],
            filestem: _match_result[3],
        };
    } else {
        return {...result,
            is_standard: false,
        }
    }
}

let page_size = 5;
let page = 1;

async function get_filelist() {
    let _res = await fetch(`https://gitea.librastalker.top/api/v1/repos/423A35C7/SharedSchoolSpace/commits?stat=false&verification=false&limit=${page_size}page=${page}`, {
        method: "GET",
        headers: {
            "accept": "application/json"
        },
        mode: "cors"
    });
    let res = await _res.json();
    return res.reduce((acc, cur) => {
        let commit_time = new Date(cur.created).toLocaleString().replaceAll('/', '-');
        cur.files.forEach((file) => {
            if (file.status === "added") {
                let file_ = pdf_filepath_to_file(file.filename);
                if (file_ === undefined) return;
                if (!file_.is_standard) return;
                acc.push({ ...file_, commit_time});
            }
        })
        return acc;
    }, []);
}

async function update_filelist() {
    entities_store.file_list.push(...await get_filelist());
    console.log(entities_store.file_list);
    page++;
}

async function current_change(data, node) {
    console.log(data, node);
    if (data.type === "file") {
        entities_store.current_file = pdf_filepath_to_file(data.path);
    }
}

const props = {
  label: 'name',
  children: 'children',
  isLeaf: 'leaf',
  disabled: 'disabled',
}

const loadNode = (
    node, resolve, reject
) => {
    console.log(node);
    let url;
    if (node.level === 0) {
        url = `https://gitea.librastalker.top/api/v1/repos/423A35C7/SharedSchoolSpace/contents/`;
    } else {
        url = `https://gitea.librastalker.top/api/v1/repos/423A35C7/SharedSchoolSpace/contents/${node.data.path}`;
    }
    return (async () => {
          let _res = await fetch(url);
          let res = await _res.json();
          console.log(node.data, res);
          if (Array.isArray(res)) {
              res.forEach(item => {
                  item.leaf = (item.type === "file");
                  // 当不是PDF时 item.disabled = true;
                  console.log(item.leaf);
              })
          }
          return res;
    })().then(value => resolve(value)).catch(error => reject(error));
}

function click_item(index) {
    entities_store.current_file_index=index;
    if (entities_store.sounds.can_play_audio)
        play_audio(tuf, "tuf");
}

function hover_item() {
    if (entities_store.sounds.can_play_audio) {
        // console.log(document.getElementById("hover_item").currentTime);
        // document.getElementById("hover_item").currentTime = 0;
        // document.getElementById("hover_item").play();
        play_audio(de, "de");
    }
}

onMounted(() => {
    // entities_store.file_list.value = await get_filelist();
    update_filelist();
})
</script>

<template>
    <keep-alive>
        <ul v-infinite-scroll="update_filelist" class="file-list" v-if="transactions_store.file_list.show.includes('by_time')">
            <li v-for="(item, index) in entities_store.file_list" :key="item"
                @click="click_item(index)" :class="entities_store.current_file_index === index ? 'active' : ''"
                @mouseenter="hover_item">
                <div class="file-dir">{{ item.filedir }}</div>
                <div class="file-stem">{{ item.filestem }}</div>
                <div class="commit-time">{{ item.commit_time }}</div>
            </li>
        </ul>
    </keep-alive>
    <!--    <v-treeview :items="file_tree_items" item-value="id" v-if="transactions_store.file_list.show === 'by_category'" activatable active-strategy="single-leaf" :open-on-click="true" v-model:active="active" @update:activated="update_activated"></v-treeview>-->
    <keep-alive>
        <el-tree v-if="transactions_store.file_list.show.includes('by_category')" :props="props" :load="loadNode" @current-change="current_change" lazy />
    </keep-alive>
</template>

<style lang="scss" scoped>
ul.tab-bar {
    display: flex;
    flex-direction: row;
    margin: 0.2em;
    padding: 0;
    height: 2em;
    li {
        list-style: none;
        text-align: center;
        display: flex;
        align-items: center;
        margin: 0 0.2em;
        padding: 0 0.5em;
        cursor: pointer;
        transition: background-color 100ms;
        &:hover,&:focus {
            background-color: #88888888;
        }
    }
}

ul.file-list {
    height: 100%;
    margin: 0;
    padding: 0;

    li {
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        list-style: none;
        height: 6em;
        width: 100%;
        box-sizing: border-box;
        text-align: center;
        align-items: center;
        border: 1px solid grey;
        //border-radius: 25px;
        transition: background-color 100ms;
        padding-left: 1em;
        padding-right: 1em;
        //不知道为啥声音的这几个好像无效
        voice-family: male;
        richness: 80;
        cue: url("@/assets/de.aac");

        &:hover, &:focus {
            background-color: var(--blog-colour-bg-hover);
            cursor: default;
        }

        &.active {
            background-color: var(--blog-colour-bg-active);
        }

        &.active:hover, &.active:focus {
            background-color: var(--blog-colour-bg-active-hover);
        }

        .file-dir {
            display: inline-flex;
            color: var(--blog-colour-lty);
            font-weight: bold;
            align-self: flex-start;
            justify-content: center;
        }

        .file-stem {
            display: inline-flex;
            color: var(--blog-colour-yzl);
            //font-weight: bold;
            align-self: flex-end;
            justify-content: center;
        }

        .commit-time {
            display: inline-flex;
            line-height: 100%;
            font-size: small;
            color: #888888aa;
        }
    }
}

</style>